package com.panasonic.web.controller.cms;

import cn.hutool.core.bean.BeanUtil;
import com.panasonic.common.constant.Constants;
import com.panasonic.common.core.domain.AjaxResult;
import com.panasonic.common.utils.ServletUtils;
import com.panasonic.web.domain.cms.CmsUser;
import com.panasonic.web.model.CmsLoginBody;
import com.panasonic.web.model.CmsLoginUser;
import com.panasonic.web.service.ICmsPermissionService;
import com.panasonic.web.security.api.CmsLoginService;
import com.panasonic.web.security.api.CmsTokenService;
import com.panasonic.web.vo.CmsUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @className: CmsLoginController
 * @description: TODO 类描述
 * @author: laiweifeng
 * @date: 2021/11/13
 **/

@Api(value = "CmsLogin", tags = "用户登录")
@RestController
@RequestMapping("/cms/login")
public class CmsLoginController {
    @Autowired
    private CmsLoginService loginService;

    @Autowired
    private ICmsPermissionService permissionService;

    @Autowired
    private CmsTokenService tokenService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping
    @ApiOperation(value = "登录")
    public AjaxResult login(@RequestBody CmsLoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getType());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation(value = "获取登录信息")
    public AjaxResult getInfo() {
        CmsLoginUser loginUser = tokenService.getCmsLoginUser(ServletUtils.getRequest());
        CmsUser user = loginUser.getUser();

        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        CmsUserVo cmsUserVO = new CmsUserVo();
        cmsUserVO.setPermissions(permissions);
        BeanUtil.copyProperties(user, cmsUserVO);
        return AjaxResult.success(cmsUserVO);
    }

}